package com.zhuj.handler;

import com.zhuj.core.InitNrpc;
import com.zhuj.core.entity.ClientRequest;
import com.zhuj.core.entity.ServerResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by Administrator on 2018/1/3.
 */
public class ServerHandler extends SimpleChannelInboundHandler<ClientRequest> {

    protected void channelRead0(ChannelHandlerContext ctx, ClientRequest request) throws Exception {
        Integer id = request.getRequestId();
        ServerResponse response = new ServerResponse();
        response.setResponseId(id);
        Object serviceImpl = InitNrpc.serviceRegistry.getService(request.getService());
        if (serviceImpl == null){
            response.setError("没有该服务类或实现类未添加注解");
            ctx.writeAndFlush(response);
            return;
        }
        Class clazz = serviceImpl.getClass();
        Method method = clazz.getMethod(request.getMethod(),request.getParamTypes());
        Object result = null;
        try{
            result = method.invoke(serviceImpl,request.getParams());
        }catch (Exception e){
            response.setError(e instanceof InvocationTargetException ?
                    ((InvocationTargetException) e).getTargetException().toString():e.toString());
            ctx.writeAndFlush(response);
            return;
        }
        response.setType(result.getClass());
        response.setResult(result);
        ctx.writeAndFlush(response);
    }
}
